package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.adapter.CommtemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.PositonKnowledgeAdapter;
import com.jp.knowledge.adapter.SecondLevelCommAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ResultSubscriber;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/5/11.
 */

public class ProductEvluationBaseFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener, OnItemListerner {

    protected static final int REFRESH_CODE = 0x01;
    protected static final int LOAD_MODE_CODE = 0x02;

    public static ProductEvluationBaseFragment newInstance(int type, int action){
        ProductEvluationBaseFragment fragment = new ProductEvluationBaseFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putInt("action", action);
        fragment.setArguments(bundle);
        return fragment;
    }

    protected Context mContext;
    protected int type;
    protected int page;
    protected int action;
    protected String tagId;

    protected View contentView;
    private CanRefreshLayout refreshLayout;
    protected RecyclerView refreshContent;
    private JpRefreshView refreshFooter;

    protected CommtemAdapter adapter;
    protected List<HeadLineData> headLineDatas;

    protected String cachePath;
    private FileCacheManager cacheManager;

    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        type = getArguments().getInt("type");
        action = getArguments().getInt("action");
        page = 1;

        cachePath = mContext.getCacheDir() + "/findData_" + type + "_" + action + ".dat";
        cacheManager = new FileCacheManager();

        initBroadCast();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null){
            contentView = View.inflate(mContext, R.layout.refresh_recycleview, null);
            refreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
            refreshContent = (RecyclerView) contentView.findViewById(R.id.can_content_view);
            refreshFooter = (JpRefreshView) contentView.findViewById(R.id.can_refresh_footer);
            refreshLayout.setOnRefreshListener(this);
            refreshLayout.setOnLoadMoreListener(this);
            refreshContent.setHasFixedSize(true);
            refreshContent.setLayoutManager(new LinearLayoutManager(mContext));
            headLineDatas = new ArrayList<>();
//            adapter = new PositonKnowledgeAdapter(mContext, headLineDatas, new SimpleDateFormat("yyyy年MM月", Locale.getDefault()));
            adapter = new SecondLevelCommAdapter(mContext, headLineDatas, new SimpleDateFormat("yyyy年MM月", Locale.getDefault()));
            adapter.setSourceType(CommtemAdapter.SOURCE_WENKU);
            refreshContent.setAdapter(adapter);
            adapter.setOnItemListener(this);

            readCache();
        }
        return contentView;
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.DETAIL_SC_BROAD.equals(action)) {
                    for (HeadLineData data : headLineDatas) {
                        if (data.getId() != null && data.getId().equals(intent.getStringExtra("id"))) {
                            data.setIsFollow(intent.getIntExtra("isCollection", 0));
                            adapter.updataAdapter(headLineDatas);
                            return;
                        }
                    }
                } else if(LocalBroadCast.COMM_CHANGE_SIZE.equals(action)){
                    adapter.changeTextSize();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.DETAIL_SC_BROAD);
        intentFilter.addAction(LocalBroadCast.COMM_CHANGE_SIZE);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<HeadLineData> headLineDataList = new ArrayList<>();
                if(headLineDatas != null) {
                    if (headLineDatas.size() <= 20) {     // 最多缓存20条数据
                        headLineDataList.addAll(headLineDatas);
                    } else {
                        for (int i = 0; i < 20; i++)
                            headLineDataList.add(headLineDatas.get(i));
                    }
                }
                cacheManager.wirteObject(headLineDataList, cachePath);
            }
        }).start();
        super.onDestroy();
    }

    public void autoRefresh(String tagId){
        this.tagId = tagId;
        if(contentView != null) {
            refreshContent.scrollToPosition(0);
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onRefresh() {
        getData(REFRESH_CODE);
    }

    @Override
    public void onLoadMore() {
        if(!refreshFooter.isLoadComplete())
            getData(LOAD_MODE_CODE);
        else
            refreshLayout.loadMoreComplete();
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<HeadLineData>>() {
            @Override
            public void call(Subscriber<? super List<HeadLineData>> subscriber) {
                List<HeadLineData> data = (List<HeadLineData>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<HeadLineData>>() {
            @Override
            public void onCompleted() {
                if(adapter.getItemCount() > 0)
                    onRefresh();
                else
                    refreshLayout.autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<HeadLineData> data) {
                headLineDatas.clear();
                if(data != null && data.size() > 0)
                    headLineDatas.addAll(data);
                updateAdapter();
                onCompleted();
            }
        });
    }

    protected void updateAdapter(){
        adapter.updataAdapter(headLineDatas);
    }

    protected void getData(int mode){
        JsonObject param = new JsonObject();
        if(mode == REFRESH_CODE){
            page = 1;
            param.addProperty("time", System.currentTimeMillis());
            param.addProperty("mode", 0);
        } else{
            page++;
            if(headLineDatas.size() > 0)
                param.addProperty("time", headLineDatas.get(headLineDatas.size()-1).getCreatetime());
            else
                param.addProperty("time", System.currentTimeMillis());
            param.addProperty("mode", 1);
        }
        param.addProperty("type", type);
        if(type == 2)
            param.addProperty("page", page);
        param.addProperty("action", action);
        param.addProperty("tagId", tagId);
        HttpHelper.getInstance(mContext).productEvluationList(param, mode, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_CODE)
            refreshLayout.refreshComplete();
        else if(requestType == LOAD_MODE_CODE)
            refreshLayout.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == REFRESH_CODE || requestType == LOAD_MODE_CODE){
            if(requestType == REFRESH_CODE) {
                headLineDatas.clear();
                refreshFooter.setLoadComplete(false);
            }
            List<HeadLineData> headLineDataList = data.getList(HeadLineData.class);
            if(headLineDataList != null && headLineDataList.size() > 0)
                headLineDatas.addAll(headLineDataList);
            else if(requestType == LOAD_MODE_CODE)
                refreshFooter.setLoadComplete(true);
            updateAdapter();
        }
    }

    @Override
    public void onItemClick(View view, int position) {
//        adapter.updateTitleColor(position);
        HeadLineData data = headLineDatas.get(position);
        CommandReceiver commandReceiver = new CommandReceiver.Builder(mContext)
                .withCompanyId(data.getCompanyId())
                .withRecordId(data.getRecordId())
                .withParameterId(data.getParameterId()+"")
                .build();
        String command = data.getCommand();
        if("ZhuanJiXiangQing".equals(command)) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", data);
            commandReceiver.setExtra(bundle);
        }
        Command commandObject = Command.create(command, commandReceiver);
        CommandInvoker.executeCommand(commandObject);

//        Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
//        intent.putExtra("id", headLineDatas.get(position).getId());
//        intent.putExtra("type", headLineDatas.get(position).getType());
//        intent.putExtra("linkTitle", headLineDatas.get(position).getTitle());
//        try {
//            intent.putExtra("linkIcon", headLineDatas.get(position).getImglist().get(0).getSrc());
//        }catch (Exception e){} finally {
//            startActivity(intent);
//        }
    }
}
